package cn.gqr.controller;

import cn.gqr.entity.Largefile;
import cn.gqr.entity.Role;
import cn.gqr.entity.User;
import cn.gqr.service.UserService;
import cn.gqr.tool.RespJson;
import cn.gqr.tool.Toolkit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService us;

    //注册买家账号
    //无需登录
    @RequestMapping("/public/registerUser")
    public Map registerUser(@RequestBody User user){
        boolean b = us.registerUser(user);
        return RespJson.pack(200,b?"注册成功":"未知错误",null);
    }

    //根据用户名称查询用户信息
    //无需登录
    @RequestMapping("/login/selectUserByUsername/{username}")
    public User doSelectUserByUsername(@PathVariable("username") String username){
        return us.selectUserByUsername(username);
    }

    //根据角色id查询权限
    //无需登录
    @RequestMapping("/login/selectUserPermissions/{roleId}")
    public List<String> doSelectUserPermissions(@PathVariable("roleId") Integer roleId){
        return us.selectUserPermissions(roleId);
    }

    //根据用户id查询角色
    //无需登录
    @RequestMapping("/login/selectUserRole/{userId}")
    public List<Role> doSelectUserRole(@PathVariable("userId") Integer userId){
        return us.selectUserRole(userId);
    }





    //获取用户信息 须登录
    @PreAuthorize("hasAuthority('user')")
    @RequestMapping("/user/userInfo")
    public Map<String,Object> getUserInfo() {
        return RespJson.pack(200,"用户信息", Toolkit.getUser());
    }

    //需登录 用户更新密码 须登录
    @PreAuthorize("hasAuthority('user')")
    @RequestMapping("/user/updateUserPassword")
    public Map<String,Object> updateUserPassword(String password){
        boolean b = us.updateUserPassword(password);
        return RespJson.pack(200,b?"修改成功":"未知错误",null);
    }

    //更新用户头像 须登录
    @PreAuthorize("hasAuthority('user')")
    @RequestMapping("/user/updateUserPicture")
    public Map<String,Object> updateUserPicture(@RequestParam(value = "pic",required = false) MultipartFile file){

        if(file == null ){
            return RespJson.pack(500,"请选择文件上传",null);
        }

        String uuid = us.updateUserPicture(file);

        return RespJson.pack(200,uuid!=null?"修改成功":"未知错误",uuid);
    }

    //更新用户名称或者电话 须登录
    @PreAuthorize("hasAuthority('user')")
    @RequestMapping("/user/updateNicknameOrPhone")
    public Map<String,Object> updateNicknameOrPhone(String nickname, String phone){

        if( (nickname==null || "".equals(nickname))  && (phone==null || "".equals(phone)) ){

            return RespJson.pack(500,"请上传参数",null);
        }

        boolean b = us.updateNicknameOrPhone(nickname, phone);

        return RespJson.pack(200,b?"更新成功":"未知错误",null);
    }


}
